import React from "react";

import Board from "./Board";
import Display from "./Display";
import ButtonArray from "./ButtonArray";

const mapping = {
    0:' ',
    1:'X',
    2:'O'
}

function update(hhh){
    return hhh.state.stateArray[hhh.state.stateArray.length-1]
}

class Game extends React.Component{
    constructor(props) {
        super(props);
        let initBoard = [
            0,0,0,
            0,0,0,
            0,0,0
        ];
        let initNextStep = 1;
        this.state = {
            stateArray: [initBoard],
            nextStep: initNextStep
        }
        this.childrenBoardClick = this.childrenBoardClick.bind(this)
        this.childrenButtonArrayClick = this.childrenButtonArrayClick.bind(this)
    }
    childrenBoardClick(position){
        let nextArray = [...(this.state.stateArray[this.state.stateArray.length-1])];
        nextArray[position] = this.state.nextStep;
        let tempStateArray = [...this.state.stateArray];
        console.log(tempStateArray)
        tempStateArray.push(nextArray)
        this.setState((state) => {
            return {
                stateArray: tempStateArray,
                nextStep: this.state.nextStep === 1 ? 2 : 1,
            }
        })
    }
    childrenButtonArrayClick(step){
        console.log(step)
        let scale = step+2;
        let tempStateArray = [...this.state.stateArray];
        while (tempStateArray.length !== scale){
            tempStateArray.pop()
        }
        this.setState((state) => {
            return {
                stateArray: tempStateArray,
                nextStep: (step+1)%2 === 0 ? 1 : 2,
            }
        })
    }
    render() {
        return (
            <div className="Game">
                <Board toFather={this.childrenBoardClick} nowMap={this.state.stateArray[this.state.stateArray.length-1]}/>
                <div className="SideBar">
                    <Display nowMap={this.state.stateArray[this.state.stateArray.length-1]}/>
                    <ButtonArray toFather={this.childrenButtonArrayClick} stepNum={this.state.stateArray.length}/>
                </div>
            </div>
        )
    }
}

export default Game;